function R = apply(lst, f, form)
%APPLY Applies a function to every element in the list
%
% [ Syntax ]
%   - apply(lst, f)
%   - R = apply(lst, f, form)
%
% [ Description ]
%   - apply(lst, f) applies the function f to each item in lst.
%
%   - R = apply(lst, f, form) applies the function f to each item in lst,
%     and collects the results to form R.
%
%     The R depends on the specified form:
%       \{:
%           - 'cell':    R is a cell array, with R{i} being f(lst{i})
%           - 'list':    R is an sllist, with R{i} being f(lst{i})
%           - 0:         R is a column vector, with R(i) being f(lst{i})
%                        (it is required that all results are scalars)
%           - 1:         R is formed by vertically concatenation of the
%                        results
%           - 2:         R is formed by horizontally concatenation of
%                        the results
%           - d:         R is formed by concatenation of the results 
%                        along d-th dimension.
%       \:}
%
% [ History ]
%   - Created by Dahua Lin, on Jan 5, 2008
%

C = cell(lst);

if nargout == 0
    cellfun(f, C);
    
else
    error(nargchk(3, 3, nargin));
    
    if ischar(form)
        switch form
            case 'cell'
                R = cellfun(f, C, 'UniformOutput', false);
            case 'list'
                R = cellfun(f, C, 'UniformOutput', false);
                R = sllist(R);
            otherwise
                error('sltoolbox:sllist:apply:invalidarg', ...
                    'Invalid form %s', form);
        end
        
    elseif isnumeric(form) && isscalar(form)
        if form == 0
            R = cellfun(f, C);
        else
            R = cellfun(f, C, 'UniformOutput', false);
            R = cat(form, R{:});
        end
        
    else
        error('sltoolbox:sllist:apply:invalidarg', ...
            'Invalid form');
    end
    
end

